﻿//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2019年12月30日 20:39:01
//------------------------------------------------------------

using System.Collections.Generic;

namespace NKG_MVVM_UI
{
    public delegate void MessageHandler<T>(object sender, MessageArgs<T> args);

    /// <summary>
    /// 充当各个ViewModel通信之间的中介者
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MessageAggregator<T>
    {
        private readonly Dictionary<string, MessageHandler<T>> _messages = new Dictionary<string, MessageHandler<T>>();

        /// <summary>
        /// 单例
        /// </summary>
        public static readonly MessageAggregator<T> Instance = new MessageAggregator<T>();

        private MessageAggregator()
        {
        }

        /// <summary>
        /// 订阅一个事件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="handler"></param>
        public void Subscribe(string name, MessageHandler<T> handler)
        {
            if (!_messages.ContainsKey(name))
            {
                _messages.Add(name, handler);
            }
            else
            {
                _messages[name] += handler;
            }
        }

        /// <summary>
        /// 分发一个事件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void Fire(string name, object sender, MessageArgs<T> args)
        {
            if (_messages.ContainsKey(name) && _messages[name] != null)
            {
                //转发
                _messages[name](sender, args);
            }
        }
    }
}